<template>
  <div class="comment-section bg-white border border-gray-200 p-5 rounded-lg dark:bg-gray-800 dark:border-gray-700 mt-4 dark:text-white">
    <h3 class="text-xl font-bold mb-4 text-gray-900 dark:text-white">文章评论</h3>
    
    <!-- 评论表单 - 仅登录用户可见 -->
    <div v-if="actuallyLoggedIn" class="comment-form mb-6">
      <div class="mb-4">
        <label for="content" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">评论内容 <span class="text-red-500">*</span></label>
        <textarea id="content" v-model="commentForm.content" rows="4" class="block p-2.5 w-full text-sm text-gray-900 bg-gray-50 rounded-lg border border-gray-300 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white" placeholder="请输入评论内容..."></textarea>
      </div>
      
      <div class="flex items-center justify-between">
        <button @click="submitComment" class="text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:outline-none focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 text-center dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800">
          发表评论
        </button>
        <span v-if="commentForm.parentId" class="text-sm text-gray-500 dark:text-gray-300">
          回复中 <button @click="cancelReply" class="text-blue-600 hover:underline dark:text-blue-400">取消</button>
        </span>
      </div>
    </div>
    
    <!-- 未登录提示 -->
    <div v-else class="mb-6 p-4 bg-gray-100 rounded-lg text-center dark:bg-gray-700 dark:text-gray-200">
      <p>请先登录! 您需要 <a @click="goToLogin" class="text-blue-500 underline cursor-pointer dark:text-blue-400">登录</a> 后才能发表评论。</p>
    </div>
    
    <!-- 评论列表 -->
    <div v-if="loading" class="text-center py-6">
      <div role="status">
        <svg aria-hidden="true" class="inline w-8 h-8 mr-2 text-gray-200 animate-spin dark:text-gray-600 fill-blue-600" viewBox="0 0 100 101" fill="none" xmlns="http://www.w3.org/2000/svg">
          <path d="M100 50.5908C100 78.2051 77.6142 100.591 50 100.591C22.3858 100.591 0 78.2051 0 50.5908C0 22.9766 22.3858 0.59082 50 0.59082C77.6142 0.59082 100 22.9766 100 50.5908ZM9.08144 50.5908C9.08144 73.1895 27.4013 91.5094 50 91.5094C72.5987 91.5094 90.9186 73.1895 90.9186 50.5908C90.9186 27.9921 72.5987 9.67226 50 9.67226C27.4013 9.67226 9.08144 27.9921 9.08144 50.5908Z" fill="currentColor"/>
          <path d="M93.9676 39.0409C96.393 38.4038 97.8624 35.9116 97.0079 33.5539C95.2932 28.8227 92.871 24.3692 89.8167 20.348C85.8452 15.1192 80.8826 10.7238 75.2124 7.41289C69.5422 4.10194 63.2754 1.94025 56.7698 1.05124C51.7666 0.367541 46.6976 0.446843 41.7345 1.27873C39.2613 1.69328 37.813 4.19778 38.4501 6.62326C39.0873 9.04874 41.5694 10.4717 44.0505 10.1071C47.8511 9.54855 51.7191 9.52689 55.5402 10.0491C60.8642 10.7766 65.9928 12.5457 70.6331 15.2552C75.2735 17.9648 79.3347 21.5619 82.5849 25.841C84.9175 28.9121 86.7997 32.2913 88.1811 35.8758C89.083 38.2158 91.5421 39.6781 93.9676 39.0409Z" fill="currentFill"/>
        </svg>
        <span class="sr-only">加载中...</span>
      </div>
    </div>
    
    <div v-else-if="comments.length === 0" class="text-center py-6 text-gray-500 dark:text-gray-300">
      暂无评论，快来发表第一条评论吧！
    </div>
    
    <div v-else class="space-y-4">
      <div v-for="comment in comments" :key="comment.id" class="p-4 border border-gray-200 rounded-lg dark:border-gray-700 dark:bg-gray-800">
        <!-- 评论头部 -->
        <div class="flex items-start">
          <img :src="comment.avatar || 'https://via.placeholder.com/150?text=用户'" :alt="comment.nickname" class="w-10 h-10 rounded-full mr-3 object-cover">
          <div class="flex-1">
            <div class="flex items-center justify-between">
              <div class="font-semibold text-gray-900 dark:text-white">{{ comment.nickname }}</div>
              <div class="text-sm text-gray-500 dark:text-gray-400">{{ formatDate(comment.createdTime) }}</div>
            </div>
            <p class="mt-2 text-gray-700 dark:text-gray-300">{{ comment.content }}</p>
            
            <!-- 点赞和回复按钮 -->
            <div class="mt-2 flex items-center text-sm">
              <button @click="likeCurrentComment(comment)" class="flex items-center text-gray-500 hover:text-blue-600 mr-4 dark:text-gray-300 dark:hover:text-blue-400">
                <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14 10h4.764a2 2 0 011.789 2.894l-3.5 7A2 2 0 0115.263 21h-4.017c-.163 0-.326-.02-.485-.06L7 20m7-10V5a2 2 0 00-2-2h-.095c-.5 0-.905.405-.905.905C11 5.42 10.518 7 10 7H6c-1.105 0-2 .895-2 2v5a7 7 0 007 7h.17"></path>
                </svg>
                {{ comment.likeCount || 0 }}
              </button>
              <button @click="replyToComment(comment)" class="flex items-center text-gray-500 hover:text-blue-600 dark:text-gray-300 dark:hover:text-blue-400">
                <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 10h10a8 8 0 018 8v2M3 10l6 6m-6-6l6-6"></path>
                </svg>
                回复
              </button>
            </div>
          </div>
        </div>
        
        <!-- 子评论 -->
        <div v-if="comment.children && comment.children.length > 0" class="mt-4 pl-12 space-y-3">
          <div v-for="child in comment.children" :key="child.id" class="p-3 bg-gray-50 dark:bg-gray-700 rounded-lg">
            <div class="flex items-start">
              <img :src="child.avatar || 'https://via.placeholder.com/150?text=用户'" :alt="child.nickname" class="w-8 h-8 rounded-full mr-2 object-cover">
              <div class="flex-1">
                <div class="flex items-center justify-between">
                  <div class="font-semibold text-gray-900 dark:text-white">{{ child.nickname }}</div>
                  <div class="text-sm text-gray-500 dark:text-gray-400">{{ formatDate(child.createdTime) }}</div>
                </div>
                <p class="mt-1 text-gray-700 dark:text-gray-300">{{ child.content }}</p>
                
                <!-- 子评论的点赞和回复按钮 -->
                <div class="mt-2 flex items-center text-sm">
                  <button @click="likeCurrentComment(child)" class="flex items-center text-gray-500 hover:text-blue-600 mr-4 dark:text-gray-300 dark:hover:text-blue-400">
                    <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14 10h4.764a2 2 0 011.789 2.894l-3.5 7A2 2 0 0115.263 21h-4.017c-.163 0-.326-.02-.485-.06L7 20m7-10V5a2 2 0 00-2-2h-.095c-.5 0-.905.405-.905.905C11 5.42 10.518 7 10 7H6c-1.105 0-2 .895-2 2v5a7 7 0 007 7h.17"></path>
                    </svg>
                    {{ child.likeCount || 0 }}
                  </button>
                  <button @click="replyToComment(comment)" class="flex items-center text-gray-500 hover:text-blue-600 dark:text-gray-300 dark:hover:text-blue-400">
                    <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 10h10a8 8 0 018 8v2M3 10l6 6m-6-6l6-6"></path>
                    </svg>
                    回复
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 分页 -->
    <div v-if="totalPages > 1" class="flex justify-center mt-6">
      <nav aria-label="Page navigation">
        <ul class="inline-flex items-center -space-x-px">
          <li>
            <button @click="changePage(currentPage - 1)" :disabled="currentPage === 1" class="block px-3 py-2 ml-0 leading-tight text-gray-500 bg-white border border-gray-300 rounded-l-lg hover:bg-gray-100 hover:text-gray-700">
              <span class="sr-only">上一页</span>
              <svg aria-hidden="true" class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" d="M12.707 5.293a1 1 0 010 1.414L9.414 10l3.293 3.293a1 1 0 01-1.414 1.414l-4-4a1 1 0 010-1.414l4-4a1 1 0 011.414 0z" clip-rule="evenodd"></path></svg>
            </button>
          </li>
          <li v-for="page in displayedPages" :key="page">
            <button @click="changePage(page)" 
                    :class="{'text-blue-600 bg-blue-50': page === currentPage, 'text-gray-500 bg-white': page !== currentPage}"
                    class="px-3 py-2 leading-tight border border-gray-300 hover:bg-gray-100 hover:text-gray-700">
              {{ page }}
            </button>
          </li>
          <li>
            <button @click="changePage(currentPage + 1)" :disabled="currentPage === totalPages" class="block px-3 py-2 leading-tight text-gray-500 bg-white border border-gray-300 rounded-r-lg hover:bg-gray-100 hover:text-gray-700">
              <span class="sr-only">下一页</span>
              <svg aria-hidden="true" class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" d="M7.293 14.707a1 1 0 010-1.414L10.586 10 7.293 6.707a1 1 0 011.414-1.414l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414 0z" clip-rule="evenodd"></path></svg>
            </button>
          </li>
        </ul>
      </nav>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue';
import { useRouter } from 'vue-router';
import { addComment, getCommentList, likeComment } from '@/api/frontend/comment';
import { getToken } from '@/composables/auth';
import { getAdminInfo } from '@/api/admin/user';
import { formatDate } from '@/composables/util';

const router = useRouter();

const props = defineProps({
  articleId: {
    type: [String, Number],
    required: true
  },
  isLoggedIn: {
    type: Boolean,
    default: false
  }
});

// 添加登录状态检查
const currentLoginStatus = ref(props.isLoggedIn);
const userInfo = ref(null);

// 检查用户是否真的登录
const checkRealLoginStatus = async () => {
  try {
    const token = getToken();
    console.log('CommentSection 检查实际token:', token);
    
    if (token) {
      // 尝试获取用户信息以验证登录状态
      const response = await getAdminInfo();
      if (response && response.data) {
        userInfo.value = response.data;
        currentLoginStatus.value = true;
        console.log('成功获取用户信息:', userInfo.value);
        return true;
      } else {
        console.error('无法获取用户信息，可能登录已过期');
        currentLoginStatus.value = false;
        return false;
      }
    } else {
      console.log('未检测到token，用户未登录');
      currentLoginStatus.value = false;
      return false;
    }
  } catch (error) {
    console.error('检查登录状态出错:', error);
    currentLoginStatus.value = false;
    return false;
  }
};

// 实际的登录状态
const actuallyLoggedIn = computed(() => {
  return currentLoginStatus.value;
});

// 评论表单数据
const commentForm = ref({
  articleId: props.articleId,
  content: '',
  parentId: null,
});

// 评论列表数据
const comments = ref([]);
const loading = ref(false);
const totalCount = ref(0);
const currentPage = ref(1);
const pageSize = ref(5);

// 计算总页数
const totalPages = computed(() => {
  return Math.ceil(totalCount.value / pageSize.value);
});

// 计算要显示的页码
const displayedPages = computed(() => {
  const pages = [];
  const maxVisiblePages = 5;
  
  if (totalPages.value <= maxVisiblePages) {
    // 如果总页数小于等于最大可见页数，则显示所有页
    for (let i = 1; i <= totalPages.value; i++) {
      pages.push(i);
    }
  } else {
    // 显示当前页附近的页
    let startPage = Math.max(currentPage.value - Math.floor(maxVisiblePages / 2), 1);
    let endPage = Math.min(startPage + maxVisiblePages - 1, totalPages.value);
    
    // 调整起始页，确保显示最大可见页数
    if (endPage - startPage + 1 < maxVisiblePages) {
      startPage = Math.max(endPage - maxVisiblePages + 1, 1);
    }
    
    for (let i = startPage; i <= endPage; i++) {
      pages.push(i);
    }
  }
  
  return pages;
});

// 监听文章ID变化，重新加载评论
watch(() => props.articleId, (newVal) => {
  if (newVal) {
    commentForm.value.articleId = props.articleId;
    fetchComments();
  }
});

// 组件挂载时初始化
onMounted(() => {
  console.log('CommentSection 挂载，登录状态:', props.isLoggedIn);
  
  if (props.articleId) {
    commentForm.value.articleId = props.articleId;
    fetchComments();
  }
  
  // 检查实际登录状态
  checkRealLoginStatus();
});

// 获取评论列表
const fetchComments = () => {
  loading.value = true;
  
  getCommentList({
    articleId: props.articleId,
    pageNum: currentPage.value,
    pageSize: pageSize.value
  }).then(response => {
    if (response && response.success) {
      comments.value = response.data.records || [];
      totalCount.value = response.data.total || 0;
    } else {
      console.error('获取评论列表失败');
    }
  }).catch(error => {
    console.error('获取评论失败:', error);
    console.error('获取评论失败，请稍后重试');
  }).finally(() => {
    loading.value = false;
  });
};

// 提交评论
const submitComment = () => {
  // 表单验证
  if (!commentForm.value.content || commentForm.value.content.trim() === '') {
    alert('评论内容不能为空');
    return;
  }
  
  // 检查登录状态
  if (!actuallyLoggedIn.value) {
    alert('请先登录后再评论');
    goToLogin();
    return;
  }
  
  // 添加文章ID
  commentForm.value.articleId = props.articleId;
  
  // 提交评论
  addComment({
    articleId: commentForm.value.articleId,
    content: commentForm.value.content,
    parentId: commentForm.value.parentId
  }).then(response => {
    if (response && response.success) {
      alert('评论发布成功！');
      
      // 重置表单
      commentForm.value.content = '';
      commentForm.value.parentId = null;
      
      // 刷新评论列表
      fetchComments();
    } else {
      alert(response.message || '评论提交失败');
    }
  }).catch(error => {
    console.error('评论提交失败:', error);
    alert('评论提交失败，请稍后重试');
  });
};

// 回复评论
const replyToComment = (comment) => {
  if (!actuallyLoggedIn.value) {
    alert('请先登录后再回复评论');
    goToLogin();
    return;
  }
  
  commentForm.value.parentId = comment.id;
  
  // 滚动到评论框
  setTimeout(() => {
    document.getElementById('content').focus();
  }, 100);
};

// 取消回复
const cancelReply = () => {
  commentForm.value.parentId = null;
};

// 点赞评论
const likeCurrentComment = (comment) => {
  if (!actuallyLoggedIn.value) {
    alert('请先登录后再点赞');
    goToLogin();
    return;
  }
  
  likeComment({ commentId: comment.id }).then(response => {
    if (response && response.success) {
      // 更新评论点赞数
      comment.likeCount = (comment.likeCount || 0) + 1;
      alert('点赞成功');
    } else {
      alert(response.message || '点赞失败');
    }
  }).catch(error => {
    console.error('点赞失败:', error);
    alert('点赞失败，请稍后重试');
  });
};

// 切换页码
const changePage = (page) => {
  if (page < 1 || page > totalPages.value) return;
  
  currentPage.value = page;
  fetchComments();
  
  // 滚动到评论区顶部
  document.querySelector('.comment-section').scrollIntoView({ behavior: 'smooth' });
};

// 跳转到登录页
const goToLogin = () => {
  router.push({ path: '/login', query: { redirect: router.currentRoute.value.fullPath } });
};
</script>

<style scoped>
.comment-section {
  font-family: 'Helvetica Neue', Arial, sans-serif;
}
</style> 